<?php
class HB_URL {
	private var $hash_array;
	
	function __construct() {
		db_register_table('url');
		$this->_gen_hash_array();
	}
	private function _gen_hash_array() {
		global $hbdb;
		$this->hash_array = (array) $hbdb->get_col("SELECT hash FROM $hbdb->url");
	}
	public function update($url_data) {
		global $hbdb;
		extract($url_date);
		if (!empty($url_id) && $hbdb->get_var("SELECT COUNT(*) FROM $hbdb->url WHERE url_id=$url_id")>0) {
			$url_update = true;
		}
		if ($url_update) { //update existed result
			$r = $hbdb->get_row("SELECT * FROM $hbdb->url WHERE url_id=$url_id");
			if (empty($ident_id)) $ident_id = $r->ident_id;
			if (empty($hash)) $hash = $r->hash;
			else {
				array_push($this->hash_array,$hash);
			}
			if (empty($url)) $url = $r->url;
			if (empty($create_date)) $create_date = $r->create_date;
			if (empty($last_visit)) $last_visit = $r->last_visit;
			if (is_null($visits)) $visits = $r->visits;
			if (!in_array($stat_mode,array('inherent','public','private','password')) $stat_mode = $r->stat_mode;
			if (is_null($stat_pass)) $stat_pass = $r->stat_pass;
			
			$sql = "UPDATE $hbdb->url SET ident_id = $ident_id, hash = '$hash', url = '$url', create_date = $create_date, last_visit = $last_visit, visits = $visits, stat_mode = '$stat_mode', stat_pass = '$stat_pass' WHERE url_id = $url_id";
		} else { //add new recode
			if (empty($ident_id)) return false;
			if (empty($hash)) return false;
			array_push($this->hash_array, $hash);
			if (empty($url)) return false;
			if (empty($create_date)) $create_date = gmmktime();
			if (empty($last_visit)) $last_visit = 0;
			if (is_null($visits)) $visits = 0;
			if (!in_array($stat_mode,array('inherent','public','private','password')) $stat_mode = 'inherent';
			if (is_null($stat_pass)) $stat_pass = '';
			$sql = "INSERT INTO $hbdb->url (ident_id,hash,url,create_date,last_visit,visits,stat_mode,stat_pass) VALUES ($ident_id,'$hash','$url',$create_date,$last_visit,$visits,'$stat_mode','$stat_pass')";
		}
		$hbdb->query($sql);
		return $hbdb->insert_id;
	}
	public function remove($url_id) {
		global $hbdb;
		$hbdb->query("DELETE FROM $hbdb->url WHERE url_id = $url_id");
		return true;
	}
	public function get($hash) {
		global $hbdb;
		return $hbdb->get_row("SELECT * FROM $hbdb->url WHERE hash = '$hash'");
	}
	public function gets($sql) {
		global $hbdb;
		$r = $hbdb->get_results("SELECT * FROM $hbdb->url $sql");
		return $r;
	}
	
	public function gen_hash($length = 4) {
		$chrs = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9');
		while (empty($rtn) || in_array($rtn, $this->hash_array)) {
			$rtn = '';
			for ($i=0;$i<$length;$i++) {
				$rtn.= $chrs(rand(0,count($chrs)-1);
			}
		}
		return $rtn;
	}
	
	public function hash_check($hash) {
		return !in_array($hash,$this->hash_array);
	}
}
$urls = new HB_URL;
?>